<template>
  <div class="page">
    <el-form size="small" :inline="true" v-if="showSearchBtn" class="query-form" ref="searchForm" :model="params"
             @keyup.enter.native="getList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item v-for="(option, index) in dataFields.filter((field)=>{
           return field.isQuery})"
                    :key="index"
                    :prop="option.model">
        <!-- <el-rate
          v-else-if="option.type === 'rate'"
          v-model="params[`${option.model}`]"
        ></el-rate> -->
        <!-- <el-color-picker
          v-else-if="option.type === 'color'"
          size="small"
          v-model="params[`${option.model}`]"
        ></el-color-picker> -->

        <!-- <el-switch
          v-else-if="option.type === 'switch'"
          size = "small"
          v-model="params[`${option.model}`]"
        >
        </el-switch> -->
        <!-- <el-slider
          v-else-if="option.type === 'slider'"
          size="small"
          v-model="params[`${option.model}`]"
        ></el-slider> -->
        <el-time-picker
          v-if="option.type === 'time'"
          size="small"
          :placeholder="option.name"
          v-model="params[`${option.model}`]">
        </el-time-picker>
        <el-date-picker
          v-else-if="option.type === 'date'"
          size="small"
          :placeholder="option.name"
          v-model="params[`${option.model}`]">
        </el-date-picker>
        <el-select
          v-else-if="option.type === 'select'"
          v-model="params[`${option.model}`]"
        >
          <el-option v-for="item in getDictList(`${option.dictType}`)" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
        <el-input v-else
                  size="small"
                  :placeholder="option.name"
                  v-model="params[`${option.model}`]"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList()" size="small" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" size="small" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 导入导出-->
    <el-dialog title="导入Excel" :visible.sync="isImportCollapse">
      <el-form size="small" :inline="true" class="query-form" ref="importForm">
        <el-form-item>
          <el-button type="default" @click="downloadTpl()" size="small">下载模板</el-button>
        </el-form-item>
        <el-form-item prop="loginName">
          <el-upload
            class="upload-demo"
            :action="`/form/generate/import`"
            :on-success="uploadSuccess"
            :data="{code}"
            :show-file-list="true">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="bg-white" :style="showSearchBtn? 'height:calc(100% - 76px)': 'height:100%'">
      <vxe-toolbar :refresh="{query: getList}" custom>
        <template #buttons>
          <el-button v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_add`)" type="primary"
                     size="small" icon="el-icon-plus" @click="add()">新建
          </el-button>
          <el-button v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_edit`)" type="warning"
                     size="small" icon="el-icon-edit-outline" @click="edit()"
                     :disabled="$refs.table && $refs.table.getCheckboxRecords().length !== 1" plain>修改
          </el-button>
          <el-button v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_del`)" type="danger"
                     size="small" icon="el-icon-delete" @click="del()"
                     :disabled="$refs.table && $refs.table.getCheckboxRecords().length === 0" plain>删除
          </el-button>
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 80px);">
        <vxe-table
          border="full"
          auto-resize
          resizable
          :loading="loading"
          :loading-config="{icon: 'vxe-icon-indicator roll', text: '加载中...'}"
          size="small"
          ref="table"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          :import-config="{}"
          :export-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="seq" width="40"></vxe-column>
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column
            v-for="(option, index) in dataFields.filter((item)=>{
          return item.isList
          })"
            :key="option.model"
            :field="option.model"
            show-overflow-tooltip
            :title="option.name">
            <template slot-scope="scope">
              <div v-if="option.type === 'html'" v-html="scope.row[`${option.model}`]"></div>
              <div v-else-if="option.type === 'color'">
                <el-color-picker disabled v-model="scope.row[`${option.model}`]"></el-color-picker>
              </div>
              <div v-else-if="option.type === 'editor'"><p
                v-html="unescapeHTML(scope.row[`${option.model}`] || '')"></p></div>
              <div v-else-if="option.type === 'imgupload'">
                <el-image
                  style="height: 50px;width:50px;margin-right:10px;"
                  :src="item.url" v-for="(item, index) in JSON.parse(scope.row[`${option.model}`] || '[]')" :key="index"
                  :preview-src-list="JSON.parse(scope.row[`${option.model}`]).map((item)=>{return item.url})">
                </el-image>
              </div>
              <div v-else-if="option.type === 'fileupload'">
                <a :href="item.url" target="_blank" :key="index"
                   v-for="(item, index) in JSON.parse(scope.row[`${option.model}`] || '[]')">
                  {{
                    decodeURIComponent(
                      item.url.substring(
                        item.url.lastIndexOf(
                          "&name="
                        ) + 6
                      )
                    )
                  }}
                </a>
              </div>
              <div v-else-if="option.type === 'checkbox' && option.options.remote === 3">

                    <span :key="index" v-for="(item, index) in JSON.parse(scope.row[`${option.model}`] || '[]')">
                      {{ getDictLabel(`${option.options.dictType}`, item) }}
                      <span v-if="index+1 !==  JSON.parse(scope.row[`${option.model}`] || '[]').length">
                        |
                      </span>
                    </span>
              </div>

              <div v-else-if="option.type === 'radio' && option.options.remote === 3">
                {{ getDictLabel(`${option.options.dictType}`, scope.row[`${option.model}`]) }}
              </div>
              <div v-else>
                <div v-if="index === 0">
                  <el-link type="primary" :underline="false"
                           v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_edit`)"
                           @click="edit(scope.row.id)">{{ scope.row[`${option.model}`] || '' }}
                  </el-link>
                  <el-link type="primary" :underline="false"
                           v-else-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_view`)"
                           @click="view(scope.row.id)">{{ scope.row[`${option.model}`] || '' }}
                  </el-link>
                  <span
                    v-else>{{ scope.row[`${option.model}`] === undefined ? '' : scope.row[`${option.model}`] }} </span>
                </div>
                <span
                  v-else>{{ scope.row[`${option.model}`] === undefined ? '' : scope.row[`${option.model}`] }} </span>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="200px" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_view`)" type="text"
                         icon="el-icon-view" size="mini" @click="view(scope.row.id)">
                查看
              </el-button>
              <el-button v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_edit`)" type="text"
                         icon="el-icon-edit" size="mini" @click="edit(scope.row.id)">
                修改
              </el-button>
              <el-button v-if="$route.query.previewMode || $auth.hasPerm(`${tableName}_del`)" type="text"
                         size="mini" icon="el-icon-delete" @click="del(scope.row.id)">
                删除
              </el-button>

            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          size="small"
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.total"
          :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
        <!-- 弹窗, 新增 / 修改 -->
        <GenerateForm ref="previewForm" @refreshDataList="getList"></GenerateForm>
      </div>
    </div>
  </div>
</template>
<script>
import UserSelect from '@/components/UserSelect'
import SelectTree from '@/components/TreeSelect'
import GenerateForm from './form'
import {getByCode, listGenerate, deGenerate} from '@/api/toolkit/pageInfo'
import {validURL} from '@/utils/validate'
import {camelCase, unescapeHTML} from "@/utils";
import {mapGetters} from "vuex";
import {getDicts} from "@/api/system/dictData";
import {getDictByKey} from "@/utils/h5ve";

export default {
  name: "Generate",
  components: {
    UserSelect,
    SelectTree,
    GenerateForm
  },
  data() {
    return {
      code: '',
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: []
      },
      params: {},
      title: '',
      tableName: '',
      dataList: [],
      options: {config: {actions: []}, list: []},
      dataFields: [],
      dictTypes: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      orderBy: '',
      isImportCollapse: false,
      loading: false
    }
  },
  created() {
    const {path} = this.$route;
    if (path.indexOf('generate') === -1) {
      // 不是动态表单不加载
      return;
    }
    const routeStr = path.split("/");
    this.code = routeStr[routeStr.length - 1];
    getByCode({code: this.code}).then(response => {
      console.log(response)
      if (response.data && response.data.pageData) {
        this.options = JSON.parse(response.data.pageData)
      } else {
        //  this.options = {'list': [], 'config': {'labelWidth': 100, 'labelPosition': 'right', 'size': 'small', 'customClass': ''}}
      }
      this.tableName = response.data.tableName
      this.dataFields = []
      this.dictTypes = []
      this.generateModel(this.options.column)
      this.dataFields.forEach((option) => {
        if (option.isQuery) {
          this.$set(this.params, option.model, undefined)
        }
      })
      console.log(this.dictTypes)
      if (this.dictTypes && this.dictTypes.length > 0) {
        this.dictTypes = Array.from(new Set(this.dictTypes));
        const promise = [];
        this.dictTypes.forEach((type) => {
          const storeDict = getDictByKey(this.dict, type)
          if (!storeDict) {
            promise.push(
              new Promise((resolve, reject) => {
                getDicts(type).then((response) => {
                  if (response.data) {
                    //console.log(response.data)
                    this.$store.dispatch("dict/setDict", {
                      key: type,
                      value: Object.freeze(response.data)
                    })
                    resolve(response);
                  }
                }).catch((err) => {
                  reject(err);
                });
              })
            );
          }
        });
        /**字典数据请求完成后查询表单数据*/
        Promise.all(promise).then(() => {
          this.getList()
        })
      } else {
        this.getList()
      }
    })
  },
  computed: {
    ...mapGetters([
      'dict'
    ]),
    showSearchBtn() {
      let searchs = this.dataFields.filter((field) => {
        return field.isQuery
      })
      return searchs.length > 0
    }
  },
  methods: {
    getList() {
      this.loading = true
      console.log(JSON.stringify(this.params))
      listGenerate({
        code: this.code,
        params: JSON.stringify(this.params),
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize
      }).then(response => {
        console.log(response)
        this.dataList = response.data
        this.tablePage.total = response.total
        this.loading = false
      })
    },
    generateModel(genList) {
      for (let i = 0; i < genList.length; i++) {
        this.dataFields.push({
          'model': genList[i].prop,
          'name': genList[i].label,
          'type': genList[i].type,
          'dictType': genList[i].dictType,
          'isList': genList[i].isList,
          'isSort': genList[i].isSort,
          'isQuery': genList[i].isQuery
        })
        if (genList[i].type == 'select' && genList[i].dictType) {
          this.dictTypes.push(genList[i].dictType)
        }
      }
      return this.dataFields
    },
    getDictList (dictType) {
      if (!dictType && dictType !== 0) {
        return []
      }
      let dicts = getDictByKey(this.dict, dictType)
      return dicts || []
    },
    getDictLabel(dictType, value, defaultLabel) {
      if ((!value && value !== 0) || (!dictType && dictType !== 0)) {
        if (defaultLabel !== undefined) {
          return defaultLabel
        } else {
          return '--'
        }
      }
      let dicts = getDictByKey(this.dict, dictType)
      if (dicts) {
        for (let i = 0; i < dicts.length; i++) {
          if (dicts[i].value && dicts[i].value.toString() === value.toString()) {
            return dicts[i].label
          }
        }
      }
      if (defaultLabel !== undefined) {
        return defaultLabel
      } else {
        return '--'
      }
    },
    // 新增
    add() {
      this.$refs.previewForm.init('add')
    },
    // 编辑
    edit(id) {
      id = id || this.$refs.table.getCheckboxRecords().map(item => {
        return item.id
      })[0]
      this.$refs.previewForm.init('edit', id)
    },
    // 当前页
    currentChangeHandle({currentPage, pageSize}) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.getList()
    },
    // 排序
    sortChangeHandle(column) {
      this.tablePage.orders = []
      if (column.order != null) {
        this.tablePage.orders.push({column: camelCase(column.property), asc: column.order === 'asc'})
      }
      this.getList()
    },
    // 查看
    view(id) {
      this.$refs.previewForm.init('view', id)
    },
    del(id) {
      let ids = id || this.$refs.table.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除所选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deGenerate({code: this.code, 'ids': ids}).then(({data}) => {
          this.loading = false
          this.$message.success(data)
          this.getList()
        }).catch(() => {
          this.loading = false
        })
      })
    },
    // 导入成功
    uploadSuccess(res, file) {
      if (res.success) {
        this.$message.success({
          dangerouslyUseHTMLString: true,
          message: res.msg
        })
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    },
    // 下载模板
    downloadTpl() {

    },
    exportExcel() {
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.page {
  background-color: #FFFFFF;
  padding: 20px;
}
</style>
